package org.hank.demoproject.socket

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import io.reactivex.android.schedulers.AndroidSchedulers
import moe.codeest.rxsocketclient.RxSocketClient
import moe.codeest.rxsocketclient.SocketClient
import moe.codeest.rxsocketclient.SocketSubscriber
import moe.codeest.rxsocketclient.meta.SocketConfig
import moe.codeest.rxsocketclient.meta.ThreadStrategy
import org.hank.demoproject.BaseViewBindingActivity
import org.hank.demoproject.Constants.MYTAG
import org.hank.demoproject.R
import org.hank.demoproject.databinding.ActivitySocketBinding
import org.hank.demoproject.utils.HexUtil
import java.net.InetSocketAddress


class SocketActivity : BaseViewBindingActivity<ActivitySocketBinding>() {
    lateinit var client: SocketClient
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_socket)
        viewBinding.btnConnect.setOnClickListener(::connectSocket)
        viewBinding.btnSend.setOnClickListener {
            sendMsg()
        }
        supportActionBar!!.title = "socket test"
    }

    override fun inflateLayout(layoutInflater: LayoutInflater): ActivitySocketBinding {
        return ActivitySocketBinding.inflate(layoutInflater)
    }

    fun connectSocket(view: View) {

        var ip = viewBinding.editSocketIp.text.toString()
        var port = viewBinding.editSocketPort.text.toString()
        var endPoint = InetSocketAddress(ip, port.toInt())
        client = RxSocketClient.create(
            SocketConfig.Builder()
                .setIp(ip)
                .setPort(port.toInt())
                .setCharset(Charsets.UTF_8)
                .setThreadStrategy(ThreadStrategy.ASYNC)
                .setTimeout(10 * 1000)
                .build()
        )

        var a = client.connect().observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : SocketSubscriber() {
                override fun onConnected() {
                    Log.d(MYTAG, "connected")
                }

                override fun onDisconnected() {
                    Log.d(MYTAG, "disconnected")
                }

                override fun onResponse(data: ByteArray) {
                    Log.d(MYTAG, "onresponse${HexUtil.bytes2HexString(data)}")
                }
            })

    }

    fun sendMsg() {
        Log.d(
            MYTAG,
            HexUtil.bytes2HexString(str2AsciiSpdh())
        )
        client.sendData(str2AsciiSpdh())
    }

    fun str2AsciiSpdh(): ByteArray {
        //emial resp message '[01][64]9.63BPE000001             150804161202FO00150000[1C]B85[1C]D0[1C]P1[1C]S000599[1C]d111         [1C]e00[1C]h0010170821[1C]q;4176662220010042=011220110816243?[1C]6[1E]E071[1E]I978[1E]N1505[1E]O0140196150804C815C5EFCB22C53120000002CDF23FA7000000000000978000000000085060111039000000A019999999999374A87EE[1E]P010922000000008CA0000000031010[1E]q019F660436004000
        //example message 9.60UM000010              210216142547FO00050000[1C]B3500[1C]F006055[1C]H480A9C7347A51FA38BF26B26C7A94DEC[1C]I1CB3484F5C43C7D3303062E7F696D64D[1C]MDC6BC7D40F3545F79DB92CBF5709EF4C[1C]S142533[1C]fDanubepay-PABK[1C]gAccepted 006055[1C]6[1E]H0P[1E]l0001   C0000000000000002   C000000000000[1C]9[1E]T0220B01010203 0101010000000000001000012000000000100000000000112500000000112510  [1C]GC3B9F3C3
        //example2 9.63TCT00001              150804161202FO00150000[1C]B85[1C]D0[1C]P1[1C]S000599[1C]d111         [1C]e00[1C]h0010170821[1C]q;417666222001 0042=011220110816243?[1C]6[1E]E071[1E]I978[1E]N1505[1E]O0140196150804C815C5EFCB22C53120000002CDF23FA7000000000000978000000000085060111039000000A019999999999374A87EE[1E]P010922000000008CA0000000031010[1E]q019F660436004000
        var fullMessage =
            "9.63BPE000001             150804161202FO001500001CB851CD01CP11CS0006221Cd111         1Ce001Ch00101708211Cq;4176662220010042=011220110816243?1C61EE0711EI9781EN15051EO0140196150804C815C5EFCB22C53120000002CDF23FA7000000000000978000000000085060111039000000A019999999999374A87EE1EP010922000000008CA00000000310101Eq019F660436004000"
        var header = "0136"
        var splitStr = fullMessage.split("1C")
        var strBuilder = StringBuilder()
        for (item in splitStr) {
            if (item.indexOf("1E") == -1) {
                strBuilder.append(HexUtil.bytes2HexString(item.toByteArray()))
            } else {
                var splitSubfield = item.split("1E")
                for (item1 in splitSubfield) {
                    strBuilder.append(item1)
                    if (splitSubfield.indexOf(item1) != splitSubfield.size - 1)
                        strBuilder.append("1E")
                }
            }
            if (splitStr.indexOf(item) != splitStr.size - 1)
                strBuilder.append("1C")
        }
        var result = header + strBuilder.toString()
        return HexUtil.hexString2Bytes(result)
    }
}